import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

// 配置的携程的域名
const CATCH_URLS = [
  'm.ctrip.com/',
  'm.ctrip.com/html5/',
  'm.ctrip.com/html5',
  'm.ctrip.com/html5/you/'
];

class WebView extends StatefulWidget {
  final String url; //跳转路径
  final String statusBarColor; //状态栏的颜色
  final String title; // 导航栏的标题
  final bool hideAppBar; //是否隐藏导航栏
  final bool backForbid;

  const WebView(
      {Key key,
      this.url,
      this.statusBarColor,
      this.title,
      this.hideAppBar,
      this.backForbid = false})
      : super(key: key);

  @override
  _WebViewState createState() => _WebViewState();
}

class _WebViewState extends State<WebView> {
  final webviewReference = FlutterWebviewPlugin();
  StreamSubscription<String> _onUrlChanged;
  StreamSubscription<WebViewStateChanged> _onStateChanged;
  StreamSubscription<WebViewHttpError> _onHttpError;
  bool exiting = false; // 默认没有返回
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 为避免重复打开，先关闭webview
    webviewReference.close();
    _onUrlChanged = webviewReference.onUrlChanged.listen((String url) {});

    // 页面导航的状态发生变化的时候的监听
    _onStateChanged =
        webviewReference.onStateChanged.listen((WebViewStateChanged state) {
      // shouldStart, startLoad, finishLoad, abortLoad
      switch (state.type) {
        case WebViewState.startLoad:
          if (_isToMain(state.url) && !exiting) {
            //不存在返回，并且返回的是h5首页
            // 判断是否是禁止返回
            if (widget.backForbid) {
              webviewReference.launch(widget.url); //是禁止返回就重新加载当前的页面
            } else {
              // 防止重复返回
              Navigator.pop(context);
              exiting = true;
            }
          }
          break;
        default:
      }
    });
    // 当我们的网页打开错误或网络的问题，这个插件提供了一个erro的监听
    _onHttpError =
        webviewReference.onHttpError.listen((WebViewHttpError error) {
      print(error);
    });
  }

  // 判断Url是不是在我们的白名单里面(是否是跳回携程的首页)
  _isToMain(String url) {
    bool contain = false;
    for (final value in CATCH_URLS) {
      //
      if (url?.endsWith(value) ?? false) {
        contain = true;
        break;
      }
    }
    return contain;
  }

  @override
  void dispose() {
    // TODO: implement dispose
    // 页面关闭的时候，关闭监听
    _onUrlChanged.cancel();
    _onStateChanged.cancel();
    _onHttpError.cancel();
    webviewReference.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 设置状态栏颜色和按钮的颜色
    String statusBarColor = widget.statusBarColor ?? 'ffffff';
    Color backButtonColor;
    if (statusBarColor == '#ffffff') {
      backButtonColor = Colors.black;
    } else {
      backButtonColor = Colors.white;
    }
    return Scaffold(
      body: Column(
        children: <Widget>[
          _appBar(Color(int.parse('0xff' + statusBarColor)), backButtonColor),
          Expanded(
            child: WebviewScaffold(
              userAgent: "", //防止携程H5页面重定向到打开携程APP ctrip://wireless/xxx的网址
              url: widget.url,
              withZoom: true, //是否可以缩放
              withLocalStorage: true, //是否启用缓存
              hidden: true, //默认状态是否隐藏
              initialChild: Container(
                color: Colors.white,
                child: Center(
                  child: Text('Waiting...'),
                ),
              ), //url还没有加载出来前的初始化加载界面，可自定义
            ),
          )
        ],
      ),
    );
  }

// 自定义的appBar状态栏
  _appBar(Color backgroundColor, Color backButtonColor) {
    if (widget.hideAppBar ?? false) {
      // 隐藏状态下
      return Container(
        color: backgroundColor,
        height: 40,
      );
    } else {
      // 非隐藏状态下
      return Container(
        // 根据刘海屏的优化方案：
        // color: backgroundColor,
        // padding: EdgeInsets.fromLTRB(0, 40, 0, 10),
        child: FractionallySizedBox(
          widthFactor: 1,
          child: Stack(
            children: <Widget>[
              GestureDetector(
                onTap: () {
                  Navigator.pop(context);
                },
                child: Container(
                  margin: EdgeInsets.only(left: 10),
                  child: Icon(
                    Icons.close,
                    color: backButtonColor,
                    size: 26,
                  ),
                ),
              ),
              Positioned(
                left: 0,
                right: 0,
                child: Center(
                    child: Text(widget.title ?? '',
                        style:
                            TextStyle(color: backButtonColor, fontSize: 20))),
              )
            ],
          ),
        ),
      );
    }
  }
}
